package com.example.demo;

/**
 * 轮转数组
 */
public class RotateArray {

    public void rotate(int[] nums, int k) {
        k = k % nums.length;
        int[] nums2 = new int[k];

        for (int i = nums.length - k; i < nums.length; i++) {
            nums2[i - nums.length + k] = nums[i];
        }

        for (int i = nums.length - 1; i >= k; i--) {
            nums[i] = nums[i - k];
        }

        for (int i = 0; i < nums2.length; i++) {
            nums[i] = nums2[i];
        }
    }

    public void rotate2(int[] nums, int k) {
        int n = nums.length;
        k = k % n;
        int[] newArr = new int[n];
        for (int i = 0; i < n; i++) {
            // 计算元素在新数组中的位置
            newArr[(i + k) % n] = nums[i];
        }
        // 将新数组复制回原数组
        System.arraycopy(newArr, 0, nums, 0, n);
    }

    public void rotate3(int[] nums, int k) {
        int n = nums.length;
        k = k % n;
        // 反转整个数组
        reverse(nums, 0, n - 1);
        // 反转前 k 个元素
        reverse(nums, 0, k - 1);
        // 反转剩余的 n - k 个元素
        reverse(nums, k, n - 1);
    }

    private void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }
}
